{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3a79ef54-63e6-429f-ba9f-590b736a7f29",
   "metadata": {},
   "source": [
    "# 3.12 对多元函数求偏导数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c90a18b9-d8e8-431c-856c-35f1e4ed05e1",
   "metadata": {},
   "source": [
    "### 1.任务描述\n",
    "函数的表达式为：$f(x,y)=x^2+2y^2+1$。当x=3，y=4时，求：\n",
    "\n",
    "- 函数值\n",
    "- 函数对x的偏导数\n",
    "- 函数对y的偏导数"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "8d7baa9c-93a2-42f3-a3c1-231cdb587f2d",
   "metadata": {},
   "source": [
    "### 2.知识准备\n",
    "\n",
    "见教程。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74ad989a-9b82-43e1-b841-e74284cd5936",
   "metadata": {},
   "source": [
    "### 3.任务分析\n",
    "\n",
    "对于给定的任务，可以通过计算得到。\n",
    "\n",
    "当$x=3$时的函数的值和导数分别为：\n",
    "\n",
    "函数值：$f(3,4)=3^2+2\\times 4^2+1=42$\n",
    "\n",
    "函数对x的偏导数：$\\left. \\frac{\\partial f(x,y)}{\\partial x} \\right | _{x=3}=2x=6$\n",
    "\n",
    "函数对y的偏导数：$\\left.\\frac{\\partial f(x,y)}{\\partial y} \\right | _{y=4}=4y=16$\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "435c6090-cfda-4f46-a550-22a368e41e4a",
   "metadata": {},
   "source": [
    "### 4.任务实施\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ec75eb6c-5da3-467d-a471-ca3b47242dd6",
   "metadata": {},
   "source": [
    "执行代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2ae9da58-e339-4d22-9f8d-ca255711d89e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tf.Tensor(6.0, shape=(), dtype=float32)\n",
      "tf.Tensor(16.0, shape=(), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "# 1，将要求偏导的变量创建为Variable对象\n",
    "x=tf.Variable(3.)\n",
    "y=tf.Variable(4.)\n",
    "# 2，创建tape对象\n",
    "with tf.GradientTape() as tape:\n",
    "    # 3，定义函数\n",
    "    f=tf.square(x) +2*tf.square(y)+1   \n",
    "    # 4，求偏导数\n",
    "    df_dx,df_dy=tape.gradient(f,[x,y])\n",
    "# 5，输出\n",
    "print(df_dx)\n",
    "print(df_dy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f2c61db-4b69-49f9-9b22-f6d2642a056d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
